package cn.texous.demo.dzs.util;

import cn.texous.demo.dzs.config.GatewayServiceProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashSet;
import java.util.Set;

/**
 * insert description here
 *
 * @author Showa.L
 * @since 2019/7/14 15:50
 */
@Component
public class PathUtils {

    private static final Set<String> START_PAH = new HashSet<>();
    private static final Set<String> MATCH_PATH = new HashSet<>();
    private static String loginUri;
    private static String checkTokenUri;

    @Autowired
    private GatewayServiceProperties gatewayServiceProperties;

    @PostConstruct
    public void init() {
        loginUri = gatewayServiceProperties.getLogingUri();
        checkTokenUri = gatewayServiceProperties.getCheckTokenUri();
        Set<String> allPath = gatewayServiceProperties.getNoAuthUris();
        allPath.forEach(p -> {
            if (p.indexOf("/**") > -1) {
                String path = p.split("\\*\\*")[0];
                START_PAH.add(path);
            } else {
                MATCH_PATH.add(p);
            }
        });
    }

    /**
     * 判断是否为不需要鉴权路径
     * @param path path
     * @return
     */
    public static boolean isNotAuthUri(String path) {
        if (MATCH_PATH.contains(path))
            return true;
        for (String p : START_PAH) {
            if (path.startsWith(p))
                return true;
        }
        return false;
    }

    public static boolean isLoginUri(String path) {
        return loginUri.equals(path);
    }

    public static boolean isCheckTokenUri(String path) {
        return checkTokenUri.equals(path);
    }

}
